package com.first.run.security;

import com.first.run.handler.FuryAuthFailureHandler;
import com.first.run.handler.FuryAuthSuccessHandler;
import com.first.run.handler.MyLogoutSuccessHandler;
import com.first.run.handler.RestAuthAccessDeniedHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.BeanIds;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.factory.PasswordEncoderFactories;
import org.springframework.security.crypto.password.PasswordEncoder;

@Slf4j
@Configuration
@EnableWebSecurity
public class WebSecurityConfigurer extends WebSecurityConfigurerAdapter {

    @Autowired
    private MyUserDetailsService userDetailsService;

    /**
     * 依赖注入自定义的登录成功处理器
     */
    @Autowired
    private FuryAuthSuccessHandler furyAuthSuccessHandler;
    /**
     * 依赖注入自定义的登录失败处理器
     */
    @Autowired
    private FuryAuthFailureHandler furyAuthFailureHandler;
    /**
     * 依赖注入自定义的注销成功的处理器
     */
    @Autowired
    private MyLogoutSuccessHandler myLogoutSuccessHandler;

    /**
     * 注册没有权限的处理器
     */
    @Autowired
    private RestAuthAccessDeniedHandler restAuthAccessDeniedHandler;

    @Bean
    public PasswordEncoder passwordEncoder() {
        return PasswordEncoderFactories.createDelegatingPasswordEncoder();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        System.out.println("configure(AuthenticationManagerBuilder auth)::::校验用户");
        //校验用户
        auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
    }

    @Bean(name = BeanIds.AUTHENTICATION_MANAGER)
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception{
        return super.authenticationManagerBean();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
//        http.authorizeRequests()
//                //"/login"不进行权限验证
//                .antMatchers("/oauth/**","/login").permitAll()
//                .anyRequest().authenticated()   //其他的需要登陆后才能访问
//                .and()
//                .formLogin()
//                //loginProcessingUrl用于指定前后端分离的时候调用后台登录接口的名称
//                .loginProcessingUrl("/login")
//                //配置登录成功的自定义处理类
//                .successHandler(furyAuthSuccessHandler)
//                //配置登录失败的自定义处理类
//                .failureHandler(furyAuthFailureHandler)
//                .and()
//                //loginProcessingUrl用于指定前后端分离的时候调用后台注销接口的名称
//                .logout().logoutUrl("/logout")
//                .logoutSuccessHandler(myLogoutSuccessHandler)
//                .and()
//                //配置没有权限的自定义处理类
//                .exceptionHandling().accessDeniedHandler(restAuthAccessDeniedHandler)
//                .and()
//                .cors()//新加入
//                .and()
//                .csrf().disable();// 取消跨站请求伪造防护


//        http
//                // 匹配oauth相关，匹配健康，匹配默认登录登出 在httpSecurity处理，，其他到ResourceServerConfigurerAdapter OAuth2处理  1
//                .requestMatchers().antMatchers("/oauth/**", "/actuator/health", "/login", "/logout")
//                .and()
//                // 匹配的全部无条件通过 permitAll 2
//                .authorizeRequests().antMatchers("/oauth/**", "/actuator/health", "/login", "/logout").permitAll()
//                // 匹配条件1的 并且不再条件2通过范围内的其他url全部需要验证登录
//                .and().authorizeRequests().anyRequest().authenticated()
//                // 启用登录验证
//                .and().formLogin().permitAll();
//        // 不启用 跨站请求伪造 默认为启用， 需要启用的话得在form表单中生成一个_csrf
//        http.csrf().disable();

        http
                .formLogin()
                .loginPage("/login")
                .loginProcessingUrl("/login")
                .failureHandler(furyAuthFailureHandler)
                .and()
                .authorizeRequests()
                .antMatchers(
                        "/token/**",
                        "/oauth/**").permitAll()
                .anyRequest().authenticated()
                //禁用跨站伪造
                .and().csrf().disable();
    }
}
